package com.jxit0573.android.lib.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;

import com.squareup.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.OkHttpClient;

/**
 * @author jia
 */
public class ImageUtils {

    private ImageUtils() {
    }

    public static void init(Context context, OkHttpClient client) {
        Picasso picasso = new Picasso.Builder(context)
                .downloader(new OkHttp3Downloader(client))
                .build();
        Picasso.setSingletonInstance(picasso);
    }

    public static void display(ImageView target, @Nullable String path, @DrawableRes int placeholderResId, @DrawableRes int errorResId) {
        if (target == null) {
            return;
        }
        RequestCreator creator;
        if (TextUtils.isEmpty(path)) {
            if (errorResId == 0) {
                return;
            } else {
                creator = Picasso.get().load(errorResId);
            }
        } else {
            creator = Picasso.get().load(path);
            if (placeholderResId != 0) {
                creator.placeholder(placeholderResId);
            }
            if (errorResId != 0) {
                creator.error(errorResId);
            }
        }
        creator.into(target);
    }

    public static void download(String url, final String path) {
        Picasso.get().load(url).into(new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                if (bitmap != null) {
                    try {
                        File file = new File(path);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        FileOutputStream fos = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        });
    }

}
